package com.hqd.jjvm.rtda.obj;

import com.hqd.jjvm.rtda.heap.JClass;
import com.hqd.jjvm.rtda.heap.classloader.JClassLoader;
import com.hqd.jjvm.rtda.slot.NumberSlot;
import com.hqd.jjvm.rtda.slot.RefSlot;

import java.io.IOException;

public class JString extends JObject {
    public JString(JClass jClass) {
        super(jClass);
    }

    public JString(JClass jClass, int size) {
        super(jClass, size);
    }

    public JString(JClass jClass, Object data) {
        super(jClass, data);
    }

    public static JString newJString(JObject jObject) {
        if (jObject == null) {
            return null;
        }
        if (jObject instanceof JString) {
            return (JString) jObject;
        }
        return new JString(jObject.getJClass(), jObject.getData());
    }

    public static JString newJString(JClassLoader loader, Object data) {
        try {
            JClass jc = loader.loadJClass(String.class.getName());
            if (data instanceof String) {
                String str = (String) data;
                JString strJObj = newJString(jc.newJObject());
                if (str != null) {
                    strJObj.getFields()[0] = new RefSlot(new JObject(jc, str.toCharArray()));
                } else {
                    strJObj.getFields()[0] = new RefSlot(new JObject(jc, null));
                }
                strJObj.getFields()[1] = new NumberSlot(str.hashCode());
                return strJObj;
            }
            return new JString(jc, data);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("class is not String ");
    }

    @Override
    public String getData() {
        return new String((char[]) ((JObject) (this.getFields()[0].getVal())).getData());
    }

    @Override
    public boolean equals(Object o) {
        JString o1 = JString.newJString((JObject) o);
        return this.getData().equals(o1.getData());
    }
}
